package cn.jinhaze.task;

import cn.jinhaze.entity.ObjectData;
import cn.jinhaze.mapper.CoreMapper;
import com.alibaba.fastjson.JSONObject;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.redis.core.ListOperations;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;
import org.springframework.util.CollectionUtils;

import java.util.ArrayList;
import java.util.List;

@Component
@RequiredArgsConstructor
@Slf4j
public class CacheToDBTask {

    private final CoreMapper coreMapper;

    private final RedisTemplate redisTemplate;

    private final MongoTemplate mongoTemplate;

    @Scheduled(cron = "0/5 * * * * ?")
    public void process() throws Exception {
        log.info("开始执行Redis -> MySQL, 异步入库任务");
        Long size = redisTemplate.opsForList().size("data");
        int MAX_SIZE = 1000;

        int processNum = size > MAX_SIZE ? MAX_SIZE : size.intValue();

        List<ObjectData> list = new ArrayList<>(processNum);
        for (int i = 0; i < processNum; i++) {
            JSONObject jsonObject = (JSONObject)redisTemplate.opsForList().rightPop("data");
            list.add(jsonObject.toJavaObject(ObjectData.class));
        }

        if (CollectionUtils.isEmpty(list)) {
            log.info("没有数据");
            return;
        }

        log.info("开始入库{}条数据", list.size());
        coreMapper.insertBatch(list);
        mongoTemplate.insertAll(list);
    }
}
